// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: "vistcx-i7q7h"
})
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  console.log(event)
  const userCardID = event.cardID
  const date = event.date
  const name = event.name
  const mobile = event.mobile
  const campus = event.campus
  console.log(wxContext.OPENID, date,userCardID)
  return db.collection('order').where({ _openid: wxContext.OPENID, date: date, cardID: userCardID, campus: campus}).get().then(res=>{
    console.log(wxContext.OPENID, date,userCardID)
    console.log(res)
    if (res.data.length == 0) {
      return  db.collection('order').add({
        data: {
          _openid: wxContext.OPENID,
          cardID: userCardID,
          name: name,
          date: date,
          mobile: mobile,
          campus: campus,
          valid: true,
          iscoming: false,
          comingTime: null
        }
      }).then(res=>{
        return { msg: '预约成功', date: userCardID,status: 200}
      }).catch(res=> {
        return { msg: '预约失败', status: 201 }
      })
    } else {
      return { msg: date + '已有预约', status: 202}
    }
  }).catch(res=>{
    return { msg: '预约失败', status: 201 }
  })

}